package com.codedef.cidaren.controller;

import com.codedef.cidaren.annotations.JwtIgnore;
import com.codedef.cidaren.common.response.Result;
import com.codedef.cidaren.common.response.ResultCode;
import com.codedef.cidaren.controller.base.BaseController;
import com.codedef.cidaren.entity.JwtParam;
import com.codedef.cidaren.entity.UserEntity;
import com.codedef.cidaren.service.UserService;
import com.codedef.cidaren.util.JwtUtils;
import com.codedef.cidaren.util.RedisUtil;
import com.codedef.cidaren.valid.AddGroup;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/api")
@RestController
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    JwtParam jwtParam;

    @Autowired
    RedisUtil redisUtil;

    @JwtIgnore
    @RequestMapping(path = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    public Result login(@RequestBody Map<String, String> requestMap) {

        log.info("LoginController.login 请求的数据 {}", requestMap);
        String username = requestMap.get("username");
        String password = requestMap.get("password");

        UserEntity dbUser = userService.userLoginCheck(username, password);
        if (dbUser != null) { //"mr".equals(username) && "123".equals(password)
            // 用户名密码验证通过
            Integer userId = dbUser.getId();
            // 生成token
            Map<String, Object> claim = new HashMap<>();
            claim.put("id", userId);
            claim.put("username", dbUser.getUsername());
            String token = JwtUtils.createToken(userId + "", claim, jwtParam);

            if (token == null) {
                log.error("===== 用户签名失败 =====");
                return null;
            }
            log.info("===== 用户{}生成签名{} =====", userId, token);

            // 生成用户的签名
            String sign = JwtUtils.getAuthorizationHeader(token);

            // 写Redis数据库
/*            dbUser.setPassword(null);
            dbUser.setSalt(null);
            redisUtil.set(sign, dbUser);*/


            return new Result(ResultCode.SUCCESS, sign);
        }
        log.info("===== 用户名或密码错误 =====");

        return new Result(ResultCode.USER_LOGIN_ERROR);
    }

    @JwtIgnore
    @RequestMapping(path = "/register", method = {RequestMethod.GET, RequestMethod.POST})
    public Result register(@Validated({AddGroup.class}) @RequestBody UserEntity user) {
        log.info("校验通过 注册controller：{}", user);

        userService.userRegister(user);

        return new Result(ResultCode.SUCCESS);
    }


}
